package com.smartstate.ems.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartstate.ems.dto.PageDTO;
import com.smartstate.ems.dto.UserDTO;
//import com.smartstate.ems.entity.*;
import com.smartstate.ems.eunm.CommonEunm;
import com.smartstate.ems.exception.MyRException;
import com.smartstate.ems.mapper.PermissionMapper;
import com.smartstate.ems.mapper.RoleMapper;
import com.smartstate.ems.mapper.UserMapper;
import com.smartstate.ems.security.MyOAuth2AccessToken;
import com.smartstate.ems.security.SecurityOAuth2ClientProperties;
import com.smartstate.ems.service.RoleService;
import com.smartstate.ems.service.UserService;
import com.smartstate.ems.vo.ResultCode;
import com.smartstate.ems.vo.ResultVO;
import com.smartstate.ems.vo.UserVO;
//import jdk.jfr.Period;
import com.smartstate.ems.entity.*;
import com.smartstate.ems.util.DateTimeUtil;
import com.smartstate.ems.util.IpUtils;
import com.smartstate.ems.util.UserUtils;
import com.smartstate.ems.util.WrapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service
@Slf4j
public class UserImpl extends ServiceImpl<UserMapper, User> implements UserService {
  @Resource
  private PasswordEncoder passwordEncoder;
  @Resource
  private RestTemplate restTemplate;
  @Value("${server.port}")
  private String serverPort;
  @Autowired
  private HttpServletRequest request;

  @Autowired
  PermissionMapper permissionMapper;


  @Resource
  private TokenStore tokenStore;

  @Resource
  private SecurityOAuth2ClientProperties securityOAuth2ClientProperties;
//  @Resource
//  SerialUtil serialUtil;
  @Resource
  UserMapper userMapper;
  @Resource
  RoleMapper roleMapper;
  @Resource
  RedisTemplate redisTemplate;
  @Resource
  RoleService roleService;



  /**
   * 根据部门名称查询用户数据
   *
   * @param item
   * @return
   */
  @Override
  public List<UserVO<User>> getAllUserAndDepartment(UserDTO<User> item) {
    List<User> users = userMapper.getAllUserAndDepartment(item);
    List<UserVO<User>> userVOList = users.stream().map((user) -> {
      UserVO<User> userVO = new UserVO<>();
      userVO.setUser(user);
      userVO.setDepartmentName(item.getDepartmentName());
      userVO.setRoleName(userMapper.getRoleByUser(user.getId()));
      return userVO;
    }).collect(Collectors.toList());
    return userVOList;
  }

  @Override
  public Page queryAllPageByDTO(PageDTO pageDTO) {
    //创建查询语句包装器和分页查询表对象
    Page<User> page = new Page(pageDTO.getPage(), pageDTO.getSize());
    //根据DTO注解封装查询语句
    Object dto = pageDTO.getDto();
    QueryWrapper<User> wrapper = WrapperUtil.convertQuery(dto, User.class);
    //返回分页查询结果
    return baseMapper.selectPage(page, wrapper);
  }

  @Override
  public String getSerialCode(String name) {
//    return serialUtil.getSerialNumber(name);
    return  "";
  }

  @Override
  public Boolean setRedisValue(String value) {
    try {
      redisTemplate.opsForValue().set("test", value);
      return true;
    } catch (Exception ex) {
      throw new MyRException("redis连接异常", "9001");
    }
  }

  @Override
  public List<UserVO<User>> findAll() {
    List<User> userList = userMapper.findAll();
    List<UserVO<User>> userVOS = userList.stream().map((user) -> {
      UserVO<User> userVO = new UserVO<>();
      userVO.setUser(user);
      userVO.setRoleName(userMapper.getRoleByUser(user.getId()));
      return userVO;
    }).collect(Collectors.toList());
    return userVOS;
  }

  /**
   * 添加用户同时设置用户角色
   *
   * @param userDTO
   * @return
   */
  @Override
  @Transactional
  public Boolean addUser(UserDTO<User> userDTO) {
//    添加用户
    String id = IdUtil.simpleUUID();
    User user = userDTO.getUser();
    user.setId(id);
    Role role = roleService.getRoleByName(userDTO.getRoleName());
//    添加用户角色信息到用户角色表
    String userRoleId = IdUtil.simpleUUID();
    boolean flag = userMapper.addUserRole(userRoleId, role.getId(), user.getId()) && this.save(user);
    return flag;
  }

  /**
   * 批量删除用户，同时删除用户角色表中的对应信息
   *
   * @param item
   * @return
   */
  @Override
  @Transactional
  public ResultVO<Boolean> removeByIds(List<String> item) {
    if (item.size() > 0) {
      if (userMapper.removeUserRoleByIds(item) > 0) {
        return ResultVO.ok();
      }
      return ResultVO.fail("失败");
    }
    return ResultVO.fail("参数缺失，请输入参数");
  }

  /**
   * 删除用户，同时删除用户角色表中的对应信息
   *
   * @param id
   * @return
   */
  @Override
  @Transactional
  public Boolean removeById(String id) {
    Boolean result = false;
    if (userMapper.removeUserRoleById(id) > 0) {
      result = true;
    }
    return result;
  }

  @Override
  public UserVO<User> getById(String id) {
    UserVO<User> userVO = new UserVO<>();
    userVO.setUser(userMapper.selectById(id));
    userVO.setRoleName(userMapper.getRoleByUser(id));
    return userVO;
  }

  /**
   * 分页查询
   *
   * @param pageDTO
   * @return
   */
  @Override
  public Page<List<UserVO>> queryAllPageByUserDTO(PageDTO<User> pageDTO) {
    //创建查询语句包装器和分页查询表对象
    Page page = new Page(pageDTO.getPage(), pageDTO.getSize());
    //根据DTO注解封装查询语句
    User dto = (User) pageDTO.getDto();
    QueryWrapper<User> wrapper = WrapperUtil.convertQuery(dto, User.class);
    // 不展示超级超级管理员( 复用枚举参数）
    wrapper.ne("USER_TYPE", CommonEunm.ISADMIN.getValue());
    if (null != dto) {
      if (StringUtils.isNotBlank(dto.getUserName())) {
        wrapper.like("USERNAME", dto.getUserName());
      }
      if (StringUtils.isNotBlank(dto.getState())) {
        wrapper.eq("state", dto.getState());
      }
    }
    wrapper.orderByDesc(CommonEunm.CREATETIME.getValue());
    List<User> list = baseMapper.selectPage(page, wrapper).getRecords();
    List<UserVO> userVOList = new ArrayList<>();
    for (User user : list) {
      UserVO userVO = new UserVO();
      String roleName = userMapper.getRoleByUser(user.getId());
      userVO.setUser(user);
      userVO.setRoleName(roleName);
      userVOList.add(userVO);
    }
    page.setRecords(userVOList);
    //返回分页查询结果
    return page;


//
//    log.info("DTO" + pageDTO.toString());
//    //        构造分页构造器
//    Page page = new Page(pageDTO.getPage(), pageDTO.getSize());
////        构造条件工作区
//    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
//    lqw.like(StringUtils.isNotEmpty(pageDTO.getDto().getUserName()), User::getUserName, pageDTO.getDto().getUserName());
//    Page iPage = super.page(page, lqw);
//    List<UserVO<User>> collect = (List<UserVO<User>>)iPage.getRecords().stream().map((user) -> {
//      UserVO<User> userVO = new UserVO<>();
//      userVO.setUser((User) user);
//      userVO.setRoleName(userMapper.getRoleByUser(((User) user).getId()));
//      return userVO;
//    }).collect(Collectors.toList());
//    iPage.setRecords(collect);
//    return iPage;
  }



  @Override
  public ResultVO<User> addNewUser(String roleId, User user) {
    if (null != user && StringUtils.isNotBlank(roleId)) {
      if (StringUtils.isNotBlank(user.getUserName()) && StringUtils.isNotBlank(user.getPhone())
              && StringUtils.isNotBlank(user.getPassword()) && StringUtils.isNotBlank(user.getNickname())) {
        // 登录账号不能重复
        User userByUsername = userMapper.getUserByUsername(user.getUserName());
        // 获取当前用户
        User loginUser=userMapper.getUser(UserUtils.getLoginUser().getId());
        if (null == userByUsername) {
          user.setId(IdUtil.objectId());
          user.setCreateUser(loginUser.getNickname());
          user.setCreateTime(new Date());
          user.setState(CommonEunm.STATUS_ON.getValue());
          user.setIsAdmin(Integer.parseInt(CommonEunm.ISNOTADMIN.getValue()));
          user.setEnterpriseId(CommonEunm.ENTERORISE.getValue());
          user.setPassword(passwordEncoder.encode(user.getPassword()));
          user.setUserType(Integer.parseInt(CommonEunm.USERTYPE.getValue()));
          if (userMapper.addNewUser(user) > 0) {
            // 用户角色数据映射添加
            if (userMapper.newUserRole(IdUtil.randomUUID(), roleId, user.getId()) > 0) {
              return ResultVO.ok(user);
            }
          }
          return  ResultVO.fail("新增失败");
        }
        return ResultVO.fail("登录账户不能重复");
      }
    }
    return ResultVO.fail("参数缺失,请输入");
  }

  @Override
  @Transactional
  public ResultVO<Boolean> updateUserById(String roleId, User user) {
    if (null != user) {
      // 获取当前登录的用户
     User loginUser=userMapper.getUser(UserUtils.getLoginUser().getId());
      user.setUpdateUser(loginUser.getNickname());
      user.setUpdateTime(new Date());
      if (userMapper.updateUserById(user) > 0) {
        // 获取用户绑定的角色
        UserAndRole userAndRole=userMapper.getUserAndRole(user.getId());
        if(null!=userAndRole){
          // 存在则更新， 否则写入
          if (userMapper.updateRoleById(roleId, user.getId()) > 0) {
            //根据用户ID 实时刷新角色数据
            userMapper.updateRoleByUserId(user.getId(),roleId);
            return ResultVO.ok();
          }
          return  ResultVO.fail(ResultCode.OPERATION_INVALID.getMessage());
        }
        else{
          // 不存在则写入
          if(userMapper.addUserRole(IdUtil.objectId(),roleId,user.getId())){
            //根据用户ID 实时刷新角色数据
            userMapper.updateRoleByUserId(user.getId(),roleId);
            return  ResultVO.ok();
          }
          return  ResultVO.fail(ResultCode.OPERATION_INVALID.getMessage());
        }
      }
      return ResultVO.fail("更新失败");
    }
    return ResultVO.fail("参数缺失，请输入用户信息");
  }

  @Override
  @Transactional
  public ResultVO<Boolean> delUserById(String id) {
    if (StringUtils.isNotBlank(id)) {
      // 超級管理員不能刪除
      User user=userMapper.getUser(id);
      if(null !=user  && CommonEunm.ONE.getValue().equals(user.getIsAdmin().toString())){
        return  ResultVO.fail("不能刪除系統管理員");
      }
      // 当前用户不能删除自己
      if(UserUtils.getLoginUser().getId().equals(id)){
        return  ResultVO.fail("禁止删除自己");
      }
      if (userMapper.removeUserRoleById(id) > 0) {
        // 根据用户ID获取其登录的token
        SimpleDateFormat sm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dt=new Date();
        Calendar ca=Calendar.getInstance();
        ca.setTime(dt);
        ca.add(Calendar.DAY_OF_MONTH,-1);
        List<TokenData>  tokenDatas=userMapper.getToken(id,sm.format(ca.getTime()),CommonEunm.STATUS_ON.getValue());
        // 注销对应的token
        setTokenFail(tokenDatas);
        //删除token_data表里面对应的数据
        userMapper.delTokenData(id);
          return ResultVO.ok();
      }
      return ResultVO.fail("删除失败");
    }
    return ResultVO.fail("参数缺失，请输入参数");
  }

  @Override
  public Page<User> getUserByNameAndStatus(PageDTO<User> pageDTO) {
    //创建查询语句包装器和分页查询表对象
    Page<User> page = new Page(pageDTO.getPage(), pageDTO.getSize());
    //根据DTO注解封装查询语句
    User dto = (User) pageDTO.getDto();
    QueryWrapper<User> wrapper = WrapperUtil.convertQuery(dto, User.class);
    wrapper.eq("USERNAME", dto.getUserName());
//    wrapper.eq("STATUS",dto.getStatus());
    //返回分页查询结果
    return baseMapper.selectPage(page, wrapper);
  }

  @Override
  public ResultVO<List<User>> getList() {
    return ResultVO.ok(userMapper.getList());
  }

  @Override
  @Transactional
  public ResultVO<Boolean> updateStatusById(String id, String state) {
    if(StringUtils.isNotBlank(id) && StringUtils.isNotBlank(state)){
      // 获取当前登录的用户
      User loginUser=userMapper.getUser(UserUtils.getLoginUser().getId());
      // 用户不能禁用自己
      if(id.equals(loginUser.getId()) && CommonEunm.STATUS_OFF.getValue().equals(state)){
        return ResultVO.fail("禁止用户禁用自己");
      }
      if(userMapper.updateStatusById(id,state,loginUser.getNickname(), DateTimeUtil.date2LocalDateTime(new Date()).toString())>0){
        // 根据用户ID获取其登录的token
        SimpleDateFormat sm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dt=new Date();
        Calendar ca=Calendar.getInstance();
        ca.setTime(dt);
        ca.add(Calendar.DAY_OF_MONTH,-1);

        List<TokenData>  tokenDatas=userMapper.getToken(id,sm.format(ca.getTime()),CommonEunm.STATUS_ON.getValue());
        // 注销对应的token
        setTokenFail(tokenDatas);
        return ResultVO.ok();
      }
    }
    return ResultVO.fail("参数缺失，请输入参数");
  }

  public void setTokenFail(List<TokenData> tokenDatas){
    if(tokenDatas.size()>0){
      for(TokenData tokenData:tokenDatas){
        log.info("tokenData:"+new String(tokenData.getToken()));
        // 根据token获取用户信息
        try {
          String tokenValue = new String(tokenData.getToken()).replace(OAuth2AccessToken.BEARER_TYPE, org.apache.commons.lang3.StringUtils.EMPTY).trim();
          OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
          tokenStore.removeAccessToken(accessToken);
          OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
          tokenStore.removeRefreshToken(refreshToken);
        }
        catch (NullPointerException e){
          log.info("注销的token已经失效，没法继续失效");
        }
        finally {
          // 注销后的token 需要修改标记生效标记
          userMapper.updateTokenByList(tokenDatas,CommonEunm.STATUS_OFF.getValue());
        }
      }
    }
  }

  @Override
  public UserVo loginByPassword(String username, String password, String code, String randomStr) {
    // 根据登录名 查询
    User user = baseMapper.getUserByUsername(username);
    UserVo vo = new UserVo();
    if(null == user){
      vo.setUsername("");
      return  vo;
    }
    // 判断该用户是否已经禁用
    if(CommonEunm.STATUS_OFF.getValue().equals(user.getState())){
      vo.setUsername(user.getUserName());
      vo.setStatus(0);
      return  vo;
    }
    if (passwordEncoder.matches(password, user.getPassword())) {
      String url = "http://127.0.0.1:" + this.serverPort + "/oauth/token?client_id="
              + securityOAuth2ClientProperties.getClientId() + "&client_secret=" + securityOAuth2ClientProperties.getClientSecret()
              + "&grant_type=password&scope=all&username=" +username+ "&password=" +password;
      MyOAuth2AccessToken myOAuth2AccessToken = restTemplate.postForObject(url, null, MyOAuth2AccessToken.class);
      BeanUtils.copyProperties(user, vo);
      log.info("userId:"+user.getId());
      Role roleByUserId = roleService.getRoleByUserId(user.getId());
      if (roleByUserId != null) {
        vo.setRoleName(roleByUserId.getRoleName());
        vo.setRoleInfo(new RoleVo().buildVo(roleByUserId));
      }else {
        roleByUserId=new Role();
        roleByUserId.setId("");
      }
      vo.setAccessToken(myOAuth2AccessToken.getAccess_token());
      //存储用户对应的token
      // 先查询，存在即覆盖，否则写入  ( 直接新增， 同一个中行户在不同的机器登录， token 不一样
//      if(userMapper.getTokenById(user.getId())>0){
//        userMapper.updateToken(user.getId(),myOAuth2AccessToken.getAccess_token());
//      }
//      else{
        userMapper.addToken(IdUtil.objectId(),myOAuth2AccessToken.getAccess_token(),user.getId(),roleByUserId.getId(),new Date(),CommonEunm.STATUS_ON.getValue());
//      }
      // 记录登录日志
      if(null !=user) {
          // 浏览器相关数据
          String chromAll = request.getHeader(CommonEunm.USERAGENT.getValue());
          String chrom = null;
          if (StringUtils.isNotBlank(chromAll)) {
            chrom = chromAll.substring(chromAll.lastIndexOf(CommonEunm.RIGHTBRACKETS.getValue()) + 1, chromAll.length());
          }
          // 获取用户对应的角色数据
//          String roleName=userMapper.getRoleByName(username);
          LoginLog loginLog = new LoginLog.LoginLogBuilder().setUsername(username).setRoleName(roleByUserId.getRoleName())
                  .setNickname(user.getNickname()).setLoginTime(DateTimeUtil.localDateTime2String(LocalDateTime.now())).setIp(IpUtils.getIP(request))
                  .setBrowser(chrom)
                  .setCreateUser(user.getNickname()).setCreateTime(LocalDateTime.now().toString()).getLoginLog();
          userMapper.addLoginLog(loginLog);
      }

      return vo;
    }
    vo.setAccessToken(null);
    vo.setUsername(username);
    vo.setStatus(1);
    return vo;
  }

  @Override
  public ResultVO<User> getUserByToken() {
    // 获取当前的登录用户
    Enumeration e= request.getHeaders("Authorization");
    while(e.hasMoreElements()){
      StringBuilder  stringBuilder= new StringBuilder(e.nextElement().toString());
      // 根据token获取用户信息
      String userId=UserUtils.getLoginUser().getId();
      log.info( " userId:"+UserUtils.getLoginUser().getId());
      return ResultVO.ok(userMapper.getUserByToken(stringBuilder.substring(stringBuilder.lastIndexOf(".")+1),userId));
    }
    return ResultVO.fail("token不存在");
  }

  @Override
  public ResultVO<List<Permission>> getPermsByToken() {
    List<Permission>  permPList=new ArrayList<>();
    List<Permission>  permCList=new ArrayList<>();
    // 获取当前的登录用户判断是否是超级管理员
    User  loginUser=userMapper.getUser(UserUtils.getLoginUser().getId());
    // 如果是超级管理员
    if(null !=loginUser && loginUser.getUserType().toString().equals(CommonEunm.ISADMIN.getValue())){

      // 顶级菜单
      permPList=permissionMapper.getListByParentId(CommonEunm.ZERO.getValue());
      // 非顶级菜单
      permCList=permissionMapper.getNoBaseList();
      // 遍历并组装树形结构
      for(Permission permission:permPList){
        List<Permission> menus = iterateMenus(permCList,permission.getId());
        permission.setList(menus);
      }
      return   ResultVO.ok(permPList);
    }
    else { // 如果是非超级管理员
      // 获取当前的登录用户登录的token
      Enumeration e= request.getHeaders("Authorization");
      while(e.hasMoreElements()){
        StringBuilder  stringBuilder= new StringBuilder(e.nextElement().toString());
        // 根据token获取用户信息
        // 获取当前登录的用户
        String userId=UserUtils.getLoginUser().getId();
        User user=userMapper.getUserByToken(stringBuilder.substring(stringBuilder.lastIndexOf(".")+1),userId);
        //根据角色ID获取用户的权限ID集合(不同的账户 token 可以是一样的 ）
        String roleId=userMapper.getRoleByToken(stringBuilder.substring(stringBuilder.lastIndexOf(".")+1),userId,CommonEunm.STATUS_ON.getValue());
        List<String>  permIds=null;
        if(StringUtils.isNotBlank(roleId)) {
          permIds = permissionMapper.getPerIdByRoleId(roleId);
          List<Permission> permissionList=new ArrayList<>();
          // 根据权限ID 集合获取对应的权限集合
          if(permIds.size()>0){
             permissionList = permissionMapper.getPermsList(permIds);
          }
          // 筛选PID是0和PID非0的 ，开始组装
          for (Permission permission : permissionList) {
            if ("0".equals(permission.getParentId().toString())) {
              permPList.add(permission);
            } else {
              permCList.add(permission);
            }
          }
          // 遍历
          for (Permission permission : permPList) {
            List<Permission> menus = iterateMenus(permCList, permission.getId());
            permission.setList(menus);
          }
        }
      }
      return  ResultVO.ok(permPList);
    }
  }

  @Override
  public ResultVO<ResultCode> updatePassword(PasswordEntity ps) {
    if (null != ps && StringUtils.isNotBlank(ps.getNewPassword()) &&
            StringUtils.isNotBlank(ps.getOldPassword())) {
      //开始修改当前登录的用户密码 ( 新旧密码存在则修改自己的密码）
      User loginUser = userMapper.getUser(UserUtils.getLoginUser().getId());
      if (null == loginUser) {
        return ResultVO.fail(ResultCode.RESOURCE_NOT_EXISTS.getMessage());
      }
      //匹配旧密码和当前登录的用户密码
       if(passwordEncoder.matches(ps.getOldPassword(),loginUser.getPassword())){
         if(userMapper.updatePassword(loginUser.getId(),passwordEncoder.encode(ps.getNewPassword()))>0){
           // 注销对应的token
           List<TokenData>  tokenDatas=userMapper.getToken(loginUser.getId(),new Date().toString(),CommonEunm.STATUS_ON.getValue());
           setTokenFail(tokenDatas);
           return  ResultVO.ok(ResultCode.SUCCESS);
         }
         return  ResultVO.fail("更新失败");
       }
       return  ResultVO.fail("密码错误，操作无效");
    }
    else if (null != ps && StringUtils.isNotBlank(ps.getNewPassword()) &&
            StringUtils.isNotBlank(ps.getComfirmPassword())) {
      log.info(" 修改别人的密码 ");
      // 修改别人的密码 （ 需要参数 用户ID ）
      if (StringUtils.isNotBlank(ps.getUserId())) {
        // 获取当前需要修改密码的用户信息
        User user = userMapper.getUser(ps.getUserId());
        if (null != user) {
          // 获取当前的登录用户信息
          User loginUser = userMapper.getUser(UserUtils.getLoginUser().getId());
          // 匹配修改者的密码（即当前登录的用户密码和前端输入的确认密码匹配 ）
          if(passwordEncoder.matches(ps.getComfirmPassword(),loginUser.getPassword())){
            if(userMapper.updatePassword(user.getId(),passwordEncoder.encode(ps.getNewPassword()))>0){
              // 注销对应的token
              List<TokenData>  tokenDatas=userMapper.getToken(user.getId(),new Date().toString(),CommonEunm.STATUS_ON.getValue());
              setTokenFail(tokenDatas);
              return  ResultVO.ok(ResultCode.SUCCESS);
            }
            return  ResultVO.fail("更新失败");
          }
          return ResultVO.fail("密码错误");
        }
        return  ResultVO.fail("不存在此用户");
      }
      return  ResultVO.fail("参数缺失，请输入目标用户ID");
    }
    return  ResultVO.fail(ResultCode.NOT_BLANK.getMessage());
  }

  /**
   *
   * @param roleId
   * @param user
   * @return
   * @Descript： 系统 管理员的初始化
   */
  @Override
  public boolean initAdmin(String roleId, User user) {
    //参数初始化
    User newUser=new User();
    newUser.setId(IdUtil.objectId());
    newUser.setCreateUser("");
    newUser.setCreateTime(new Date());
    newUser.setState(CommonEunm.STATUS_ON.getValue());
    newUser.setIsAdmin(Integer.parseInt(CommonEunm.ISNOTADMIN.getValue()));
    newUser.setEnterpriseId(CommonEunm.ENTERORISE.getValue());
    newUser.setPassword(passwordEncoder.encode(user.getPassword()));
    newUser.setUserName(user.getUserName());
    newUser.setNickname(user.getNickname());
    newUser.setPhone(user.getPhone());
    newUser.setUserType(Integer.parseInt(CommonEunm.ISADMIN.getValue()));
    if (userMapper.addNewUser(newUser) > 0) {
      if (userMapper.newUserRole(IdUtil.randomUUID(), roleId, newUser.getId()) > 0) {
        return true;
      }
    }
    return  false;
  }


  public ResultVO<ResultCode> updatePw(String oldPw,String newPw,String conPw,User user){
    // 匹配密码( 新密码和确认密码需要前端去检验 ）
    if(passwordEncoder.matches(oldPw,user.getPassword())){
      if(newPw.equals(conPw)){
        if(userMapper.updatePassword(user.getId(),passwordEncoder.encode(newPw))>0){
          // 注销对应的token
          List<TokenData>  tokenDatas=userMapper.getToken(user.getId(),new Date().toString(),CommonEunm.STATUS_ON.getValue());
          setTokenFail(tokenDatas);
          return  ResultVO.ok(ResultCode.SUCCESS);
        }
      }
      return  ResultVO.fail(ResultCode.VERIFICATION_FAIL.getMessage());
    }
    return  ResultVO.fail(ResultCode.VERIFICATION_FAIL.getMessage());
  }

  public List<Permission> iterateMenus(List<Permission> menuVoList,String pid){
    List<Permission> result = new ArrayList<Permission>();
    for (Permission menu : menuVoList) {
      //获取菜单的id
      String menuid = menu.getId();
      //获取菜单的父id
      String parentid = menu.getParentId();
      if(com.smartstate.ems.util.StringUtils.isNotBlank(parentid)){
        if(parentid.equals(pid)){
          //递归查询当前子菜单的子菜单
          List<Permission> iterateMenu = iterateMenus(menuVoList,menuid);
          menu.setList(iterateMenu);
          result.add(menu);
        }
      }
    }
    return result;
  }

}
